import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { exchangeLink } from '@/services/previewService';

const Index = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // 手动解析URL参数的函数
  const getUrlParams = () => {
    console.log('开始解析URL参数');
    console.log('当前完整URL:', window.location.href);
    console.log('window.location.search:', window.location.search);
    console.log('window.location.hash:', window.location.hash);
    
    // 尝试从search中获取参数
    const searchParams = new URLSearchParams(window.location.search);
    let mode = searchParams.get('mode');
    let keyBase64 = searchParams.get('keyBase64');
    let accessToken = searchParams.get('accessToken');
    
    console.log('从search获取的参数:', { mode, keyBase64, accessToken });
    
    // 如果search中没有参数，尝试从hash中获取
    if ((!mode || !keyBase64) && window.location.hash) {
      const hashPart = window.location.hash;
      console.log('尝试从hash中解析参数:', hashPart);
      
      // 检查hash中是否包含查询参数
      const questionMarkIndex = hashPart.indexOf('?');
      if (questionMarkIndex !== -1) {
        const queryString = hashPart.substring(questionMarkIndex + 1);
        console.log('从hash中提取的查询字符串:', queryString);
        
        const hashParams = new URLSearchParams(queryString);
        mode = mode || hashParams.get('mode');
        keyBase64 = keyBase64 || hashParams.get('keyBase64');
        accessToken = accessToken || hashParams.get('accessToken');
        
        console.log('从hash获取的参数:', { mode, keyBase64, accessToken });
      }
    }
    
    // 如果还是没有参数，尝试解析完整URL
    if ((!mode || !keyBase64) && !accessToken) {
      const fullUrl = window.location.href;
      const questionMarkIndex = fullUrl.indexOf('?');
      if (questionMarkIndex !== -1) {
        const queryString = fullUrl.substring(questionMarkIndex + 1);
        console.log('从完整URL提取的查询字符串:', queryString);
        
        // 移除可能的hash部分
        const cleanQueryString = queryString.split('#')[0];
        console.log('清理后的查询字符串:', cleanQueryString);
        
        const urlParams = new URLSearchParams(cleanQueryString);
        mode = mode || urlParams.get('mode');
        keyBase64 = keyBase64 || urlParams.get('keyBase64');
        accessToken = accessToken || urlParams.get('accessToken');
        
        console.log('从完整URL获取的参数:', { mode, keyBase64, accessToken });
      }
    }
    
    const finalParams = { mode, keyBase64, accessToken };
    console.log('最终解析的参数:', finalParams);
    return finalParams;
  };

  useEffect(() => {
    console.log('Index组件 useEffect 触发');
    
    // 获取URL参数
    const { mode, keyBase64, accessToken } = getUrlParams();
    
    console.log('获取到的URL参数:', { mode, keyBase64, accessToken });

    // 如果有必要参数，则调用交换链接接口
    if (mode && keyBase64) {
      console.log('参数验证通过，准备调用交换链接接口');
      handleExchangeLink(mode, keyBase64, accessToken);
    } else {
      console.log('参数不完整，保持透明背景');
      console.log('缺失的参数 - mode:', !mode ? '缺失' : '存在', 'keyBase64:', !keyBase64 ? '缺失' : '存在');
    }
  }, []);

  const handleExchangeLink = async (mode, keyBase64, accessToken) => {
    console.log('开始执行 handleExchangeLink 函数');
    console.log('传入参数:', { mode, keyBase64, accessToken });
    
    setLoading(true);
    setError(null);

    try {
      console.log('准备调用 exchangeLink 服务');
      const result = await exchangeLink(mode, keyBase64, accessToken);
      console.log('exchangeLink 服务返回结果:', result);
      
      if (result.success) {
        const { pagePath, fileList } = result.data;
        console.log('接口调用成功，准备跳转页面');
        console.log('跳转路径:', pagePath);
        console.log('文件列表:', fileList);
        
        // 构建跳转URL，只携带 accessToken 参数
        const targetPath = accessToken 
          ? `${pagePath}?accessToken=${encodeURIComponent(accessToken)}`
          : pagePath;
        
        console.log('最终跳转路径:', targetPath);
        console.log('执行页面跳转...');
        
        // 跳转到指定页面，并传递文件信息
        navigate(targetPath, {
          state: { fileList }
        });
        console.log('页面跳转命令已执行');
      } else {
        console.error('接口调用失败:', result.error);
        setError(result.error || '获取预览信息失败');
      }
    } catch (err) {
      console.error('handleExchangeLink 异常:', err);
      setError('系统错误，请稍后重试');
    } finally {
      console.log('handleExchangeLink 执行完成，设置loading为false');
      setLoading(false);
    }
  };

  // 返回透明背景的空div，不显示任何内容
  return <div className="min-h-screen bg-transparent" />;
};

export default Index;
